package controller;

import com.root.health.bean.*;
import com.root.health.service.CorrelationService;
import com.root.health.service.MedicationService;
import com.root.health.service.MedicineService;
import com.root.health.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Controller
public class MedicationController {
    @Autowired
    MedicationService medicationService;
    @Autowired
    MedicineService medicineService;
    @Autowired
    UserService userService;
    @Autowired
    CorrelationService correlationService;
    @Lazy
    @Autowired
    LoginController loginController;
    /**
     *
     * 服药信息添加
     */
    @PostMapping("medication")
    public String medicationPage(UserInfo userInfo,MedicationInfo medicationInfo, HttpServletRequest request,HttpSession session,Model model){
        if(session.getAttribute("loginUser") == null){
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg","请重新登录");
            //回到登录页面
            return "login";
        }//登录拦截器
        UserInfo tempo_user = (UserInfo) session.getAttribute("loginUser");
        userInfo = userService.getUserbyName(tempo_user.getUserName());
        //由于Session传递来的用户是前端页面中输入的用户实体类，没有被数据库增加userid，所以需要再从数据库查询一次当前用户获取userid
        medicationInfo.setUserId(userInfo.getUserId());
        //将当前用户id放入medicationInfo的userid中
        String strtime = request.getParameter("MedicationTimeForm");
        String time_oclock = strtime.substring(0,2);
        String time_minute = strtime.substring(2,5);
        String time_frame = strtime.substring(6);
        if(time_frame.equals("下午")){
            int int_oclock = Integer.parseInt(time_oclock);
            int_oclock+=12;
            time_oclock = String.valueOf(int_oclock);
            System.out.println(strtime);
        }
        strtime = time_oclock + time_minute + ":00";
        //将用户输入的12小时制转换为24小时制
        Date date = new Date(System.currentTimeMillis());
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateNow = dateFormat.format(date)+" "+strtime;
        System.out.println(dateNow);
        Timestamp time = Timestamp.valueOf(dateNow);
        medicationInfo.setMedicationTime(time);
        //将转换之后的strtime放入MedicationTime
        if(userInfo.getRole().equals("parents")){
            if(medicationService.medicationCheck(medicationInfo.getMedicineName(),medicationInfo.getMedicationTime(),medicationInfo.getMedicationDose(),
                    medicationInfo.getMedicationAlert(),medicationInfo.getMedicationDone(),medicationInfo.getUserId())==null) {
                medicationService.medicationInfo(medicationInfo.getMedicineName(), medicationInfo.getMedicationTime(), medicationInfo.getMedicationDose(),
                        medicationInfo.getMedicationAlert(), medicationInfo.getMedicationDone(), medicationInfo.getUserId());
                model.addAttribute("successHref","medicationManager");
                return "success";
            }else {
                model.addAttribute("errormsg","服药信息添加重复");
                return "error";
            }
        }else if(userInfo.getRole().equals("children")){
            //如果当前用户角色为子女，则在添加之前先跳转到选择已关联的父母角色页面，再跳转到子女角色添加方法
            session.setAttribute("medicationInfo",medicationInfo);
            List<UserInfo> List_corruser = new LinkedList<UserInfo>();
            List<Map<String,Object>> userMapList = new LinkedList<>();
            Map<String,Object> userMap;
            List<CorrelationInfo> List_corr = correlationService.parentidgetByid(userInfo.getUserId());
            for (int i = 0; i < List_corr.toArray().length; i++) {
                int finalI = i;
                UserInfo a_user = userService.getUserbyId(List_corr.get(i).getParentid());
                userMap = new HashMap<>(){{
                    put("id",List_corr.get(finalI).getId());
                    put("username",a_user.getUserName());
                    put("realname",a_user.getRealname());
                    put("role","父母");
                }};
                //将查询出的id放入getUserbyId查询对应user信息，并将user信息放入List中准备遍历给前端
                userMapList.add(userMap);
            }
            model.addAttribute("userMapList",userMapList);
            return "selectuserMedication";
        }else{
            model.addAttribute("errormsg","添加服药信息用户角色错误");
            return "error";
        }
    }
    /**
     *
     * 子女用户添加服药信息
     */
    @GetMapping("childrenMedicationAdd")
    public String childrenMedicationAdd(String username,MedicationInfo medicationInfo,HttpSession session,Model model){
        if(session.getAttribute("loginUser") == null){
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg","请重新登录");
            //回到登录页面
            return "login";
        }
        session.setAttribute("username",username);
        medicationInfo = (MedicationInfo)session.getAttribute("medicationInfo");
        medicationInfo.setUserId(userService.getUserbyName(username).getUserId());
        if(medicationService.medicationCheck(medicationInfo.getMedicineName(),medicationInfo.getMedicationTime(),medicationInfo.getMedicationDose(),
                medicationInfo.getMedicationAlert(),medicationInfo.getMedicationDone(),medicationInfo.getUserId())==null) {
            medicationService.medicationInfo(medicationInfo.getMedicineName(), medicationInfo.getMedicationTime(), medicationInfo.getMedicationDose(),
                    medicationInfo.getMedicationAlert(), medicationInfo.getMedicationDone(), medicationInfo.getUserId());
            //做重复性校验防止信息重复添加
            model.addAttribute("successHref","medicationManager");
            return "success";
        }else{
            model.addAttribute("errormsg","子女用户添加服药信息重复");
            return "error";
        }
    }
    /**
     *
     * 查询功能中间方法
     */

    @PostMapping("medicationLinkAdd")
    public String medicationLinkAdd(){

        return "medicationInfo";
    }

    @GetMapping("medicationLinkAdd")
    public String medicationLinkAdd(long medId,HttpSession session,Model model){
        if(session.getAttribute("loginUser") == null){
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg","请重新登录");
            //回到登录页面
            return "login";
        }//登录拦截器
        MedicineInfo medicineInfo = medicineService.medById(medId);
        session.setAttribute("medicationByMedName",medicineInfo.getMedicineName());
        return "medicationInfo";
    }
    //从药品查询页面携带药品名参数传递到添加服药信息页面

    /**
     *
     * 服药信息查询
     */
    @GetMapping("medicationManager")
    public String selectmedication(UserInfo userInfo,MedicationInfo medicationInfo,Model model,HttpSession session) {
        if (session.getAttribute("loginUser") == null) {
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg", "请重新登录");
            //回到登录页面
            return "login";
        }//登录拦截器
        UserInfo tempo_user = (UserInfo) session.getAttribute("loginUser");
        userInfo = userService.getUserbyName(tempo_user.getUserName());
        //由于Session传递来的用户是前端页面中输入的用户实体类，没有被数据库增加userid，所以需要再从数据库查询一次当前用户获取userid
        List<MedicationInfo> medicationList;
        List<Map<String, Object>> medicationMapList = new LinkedList<>();
        Map<String, Object> medicationMap;
        if (userInfo.getRole().equals("parents")) {
            medicationList = medicationService.selectmedication(userInfo.getUserId());
            for (int i = 0; i < medicationList.toArray().length; i++) {
                int finalI = i;
                String medDone;
                String medClass;
                if (medicationList.get(finalI).getMedicationDone() == 0) {
                    medDone = "未服药";
                    medClass = "label label-danger";
                } else if (medicationList.get(finalI).getMedicationDone() == 1) {
                    medDone = "已服药";
                    medClass = "label label-success";
                } else {
                    medDone = "信息出错";
                    medClass = "label label-warning";
                }
                String stryear = String.valueOf(medicationList.get(finalI).getMedicationTime()).substring(0,10);
                String strtime = String.valueOf(medicationList.get(finalI).getMedicationTime()).substring(11,19);
                String time = stryear +"\n"+strtime;

                medicationMap = new HashMap<>() {{
                    put("id",medicationList.get(finalI).getMedicationId());
                    put("medname", medicationList.get(finalI).getMedicineName());
                    put("time", time);
                    put("dose", medicationList.get(finalI).getMedicationDose());
                    put("done", medDone);
                    put("realname", userService.getUserbyId(medicationList.get(finalI).getUserId()).getRealname());
                    put("medClass",medClass);
                }};
                medicationMapList.add(medicationMap);
            }
            model.addAttribute("medicationMapList", medicationMapList);
            return "medicationManager";//如果当前用户角色为父母，仅查询该用户的体检信息
        } else {// if(userInfo.getRole().equals("children"))
            //如果当前用户角色为子女，则先从关联信息表查询该角色关联用户id，再以list形式查询对应id的体检信息
            List<CorrelationInfo> list_corr = correlationService.parentidgetByid(userInfo.getUserId());
            for (int i = 0; i < list_corr.toArray().length; i++) {
                if (list_corr.get(i) == null) {
                    break;//若本次循环中list_corr不存在，则跳出整个循环防止出现数组越界错误
                }
                List<MedicationInfo> a_list = medicationService.selectmedication(list_corr.get(i).getParentid());
                //测试System.out.println("a_list:"+a_list+"a_list的长度为:"+a_list.toArray().length);
                for (int j = 0; j < a_list.toArray().length; j++) {
                    if (a_list.get(j) == null) {
                        break;//若本次循环中a_list不存在，则跳出整个循环防止出现数组越界错误
                    }
                    int finalJ = j;
                    String medDone;
                    String medClass;
                    if (a_list.get(finalJ).getMedicationDone() == 0) {
                        medDone = "未服药";
                        medClass = "label label-danger";
                    } else if (a_list.get(finalJ).getMedicationDone() == 1) {
                        medDone = "已服药";
                        medClass = "label label-success";
                    } else {
                        medDone = "信息出错";
                        medClass = "label label-warning";
                    }
                    String stryear = String.valueOf(a_list.get(finalJ).getMedicationTime()).substring(0,10);
                    String strtime = String.valueOf(a_list.get(finalJ).getMedicationTime()).substring(11,19);
                    String time = stryear +"\n"+strtime;

                    medicationMap = new HashMap<>() {{
                        put("id",a_list.get(finalJ).getMedicationId());
                        put("medname", a_list.get(finalJ).getMedicineName());
                        put("year", stryear);
                        put("time", strtime);
                        put("dose", a_list.get(finalJ).getMedicationDose());
                        put("done", medDone);
                        put("realname", userService.getUserbyId(a_list.get(finalJ).getUserId()).getRealname());
                        put("medClass",medClass);
                    }};
                    medicationMapList.add(medicationMap);
                    //将已检索信息放入Map中传入前端（因为userName不在examInfo中，所以需要用Map整合信息
                }
            }
            model.addAttribute("medicationMapList", medicationMapList);
            return "medicationManager";
        }
    }
    /**
     *
     * 从服药查询页面携带参数实现删除操作
     */

    @PostMapping("medicationDel")
    public String medicationLinkDel(){

        return "main";
    }

    @GetMapping("medicationDel")
    public String medicationLinkDel(long medicationid,HttpSession session,Model model){
        if(session.getAttribute("loginUser") == null){
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg","请重新登录");
            //回到登录页面
            return "login";
        }//登录拦截器
        session.setAttribute("medicationid",medicationid);
        medicationService.medicationDel(medicationid);
                    model.addAttribute("successHref","medicationManager");
            return "success";
    }
    /**
     *
     * 修改操作中间方法
     */
    @GetMapping("medicationLinkUpd")
    public String medicationLinkUpd(long medicationid,HttpSession session,Model model){
        if(session.getAttribute("loginUser") == null){
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg","请重新登录");
            //回到登录页面
            return "login";
        }//登录拦截器
        MedicationInfo medicationInfo = medicationService.selectmedicationByMedicationId(medicationid);
        UserInfo userInfo = userService.getUserbyId(medicationInfo.getUserId());
        model.addAttribute("userName",userInfo.getRealname());
        session.setAttribute("medicationid",medicationid);
        return "medicationUpd";
    }
    /**
     *
     * 从服药查询页面携带参数实现修改操作
     */
    @PostMapping("medicationUpd")
    public String medicationUpd(){
        return "medicationUpd";
    }
    @GetMapping("medicationUpd")
    public String medicationUpd(MedicationInfo medicationInfo,long medicationid,HttpSession session,HttpServletRequest request,Model model){
        if(session.getAttribute("loginUser") == null){
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg","请重新登录");
            //回到登录页面
            return "login";
        }//登录拦截器
        session.setAttribute("medicationid",medicationid);
        String strtime = request.getParameter("MedicationTimeForm");
        String time_oclock = strtime.substring(0,2);
        String time_minute = strtime.substring(2,5);
        String time_frame = strtime.substring(6);
        if(time_frame.equals("下午")){
            int int_oclock = Integer.parseInt(time_oclock);
            int_oclock+=12;
            time_oclock = String.valueOf(int_oclock);
            System.out.println(strtime);
        }
        strtime = time_oclock + time_minute + ":00";
        //将用户输入的12小时制转换为24小时制
        Date date = new Date(System.currentTimeMillis());
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateNow = dateFormat.format(date)+" "+strtime;
        System.out.println(dateNow);
        Timestamp time = Timestamp.valueOf(dateNow);
        medicationInfo.setMedicationTime(time);
        //将转换之后的strtime放入MedicationTime
        medicationService.medicationUpd(medicationInfo.getMedicationTime(),medicationInfo.getMedicationDose(),
                medicationInfo.getMedicationAlert(),medicationInfo.getMedicationDone(),medicationid);
                    model.addAttribute("successHref","medicationManager");
            return "success";
    }

    /**
     * 服药信息完成
     * @param medicationId
     * @param session
     * @param model
     * @return
     */
    @GetMapping("medicationDone")
    public String medicationDone(long medicationId,HttpSession session,Model model){
        try {
            medicationService.medicationDone(medicationId);
            return loginController.mainPage(session,model);
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }
}
